import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;
    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true) {
            Socket socket = serverSocket.accept();
            possess(socket);
        }
    }
    private void possess(Socket clientSocket)  {
        System.out.println("客户端上线");
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            Scanner scanner = new Scanner(inputStream);
            while (true) {
                if(!scanner.hasNext()) {
                    System.out.println("客户端下线");
                    break;
                }
                String request = scanner.next();
                String response = possessFun(request);
                outputStream.write(response.getBytes());
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
    private String possessFun(String request) {
        return request+" \n";
    }
}
